﻿using System;
using System.Linq;
using Microsoft.SharePoint;

namespace Xodeuz.SP.Common
{
    public class SPExportHelper
    {
        private const string OWSSVR_FORMAT_EXCEL = "/_vti_bin/owssvr.dll?CS=109&Using=_layouts/query.iqy&List={0}&View={1}&CacheControl=1";
        private const string OWSSVR_FORMAT_XML = "/_vti_bin/owssvr.dll?Cmd=Display&List={0}&View={1}&Query=*&XMLDATA=TRUE";
        /// <summary>
        /// Redirect to OWSSVR.dll export to excel feature
        /// </summary>
        public static string ExportToExcel(String listTitle, String viewName)
        {
            SPList list = SPContext.Current.Web.Lists.TryGetList(listTitle);

            if(list == null)
                throw new ArgumentNullException("List with title: " + listTitle + " was not found on web:" + SPContext.Current.Web.Url);

            SPView view = list.Views.Cast<SPView>().FirstOrDefault(v => v.Title.Equals(viewName));

            if (view == null)
                throw new ArgumentNullException("View with the name: " + viewName + " was not found in list:" + listTitle);

            return SPContext.Current.Web + String.Format(OWSSVR_FORMAT_EXCEL, list.ID, view.ID);
        }

        /// <summary>
        /// Redirect to OWSSVR.dll export to xml feature
        /// NOTE: Will take all fields, view is only needed for export url but is never used
        /// </summary>
        public static string ExportToXml(String listTitle, String viewName)
        {
            SPList list = SPContext.Current.Web.Lists.TryGetList(listTitle);

            if (list == null)
                throw new ArgumentNullException("List with title: " + listTitle + " was not found on web:" + SPContext.Current.Web.Url);

            SPView view = list.Views.Cast<SPView>().FirstOrDefault(v => v.Title.Equals(viewName));

            if (view == null)
                throw new ArgumentNullException("View with the name: " + viewName + " was not found in list:" + listTitle);

            return SPContext.Current.Web + String.Format(OWSSVR_FORMAT_XML, list.ID, view.ID);
        }
    }
}
